import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Table,
  Form,
  Icon,
  Button,
  Tag,
  Popconfirm,
  BackTop,
  message,
  notification,
} from 'antd';
import OperateModal from './OperateModal';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';

import styles from './List.less';

@connect(({ productType, loading }) => ({
  productType,
  loading: loading.models.productType,
}))
@Form.create()
class List extends PureComponent {
  state = {
    addNewVisible: false,
    updateItemVisible: false,
    metaData: {},
    customData: {
      count: 0,
      list: [],
    },
    pageNo: 1,
    pageSize: 10,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { pageNo, pageSize } = this.state;

    dispatch({
      type: 'productType/list',
      payload: { pageNo, pageSize },
    }).then(() => {
      const {
        productType: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  }

  handleEditClick = record => {
    this.setState({ metaData: record });
    this.setState({ updateItemVisible: true });
  };

  refreshGrid = () => {
    const { dispatch } = this.props;

    const params = {};
    dispatch({
      type: 'productType/list',
      payload: params,
    }).then(() => {
      const {
        productType: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      // this.setState({
      //   formValues: values,
      // });

      dispatch({
        type: 'productType/list',
        payload: {
          ...values,
          pageNo: 1,
          pageSize,
        },
      }).then(() => {
        const {
          productType: { data },
        } = this.props;
        this.setState({ customData: data });
      });
    });
  };

  showAddNewModal = record => {
    this.setState({ metaData: record });
    this.setState({
      addNewVisible: true,
    });
  };

  afterAddNewModalOk = () => {
    this.setState({
      addNewVisible: false,
    });
    this.refreshGrid();
  };

  afterAddNewModalCancel = () => {
    this.setState({
      addNewVisible: false,
    });
  };

  afterUpdateItemModalOk = () => {
    this.setState({
      updateItemVisible: false,
    });
    this.refreshGrid();
  };

  afterUpdateItemModalCancel = () => {
    this.setState({
      updateItemVisible: false,
    });
  };

  deleteItem = record => {
    const { dispatch } = this.props;

    dispatch({
      type: 'productType/remove',
      payload: {
        productTypeId: record.productTypeId,
      },
    }).then(() => {
      const {
        productType: { data },
      } = this.props;
      const { status: statusCode, message: messageText } = data;
      if (statusCode === 200) {
        notification.success({
          placement: 'bottomRight',
          message: '操作结果',
          description: '数据已经删除成功，请进行后续操作。',
        });

        this.refreshGrid();
      } else {
        notification.error({
          placement: 'bottomRight',
          message: '操作结果',
          description: messageText,
        });
      }
    });
  };

  cancelDelete = () => {
    message.info('已取消删除操作。');
  };

  renderSimpleForm() {
    const { dispatch } = this.props;
    const {
      customData: { list },
      addNewVisible,
      metaData,
    } = this.state;
    return (
      <Fragment>
        <div
          style={{
            width: '100%',
            borderBottom: '1px solid #e8e8e8',
            padding: '10px 0px',
            textAlign: 'right',
            background: '#fff',
            borderRadius: '0 0 4px 4px',
          }}
        >
          <Button type="primary" onClick={this.showAddNewModal}>
            {'新增分类'}
          </Button>
          <OperateModal
            visible={addNewVisible}
            mode="add"
            showRoot
            treeData={list}
            metaData={metaData}
            canSelect={false}
            dispatch={dispatch}
            afterOK={this.afterAddNewModalOk}
            afterCancel={this.afterAddNewModalCancel}
          />
        </div>
      </Fragment>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { loading, dispatch } = this.props;
    const {
      customData: { list },
      metaData,
      updateItemVisible,
      category,
    } = this.state;
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        align: 'left',
        render: (val, record) => {
          const tag =
            record.defaultSet === '1' ? (
              <Tag color="#7a8aa2" style={{ marginLeft: '4px' }}>
                默认
              </Tag>
            ) : (
              ''
            );
          return (
            <Fragment>
              {val}
              {tag}
            </Fragment>
          );
        },
      },
      {
        title: '操作',
        width: 226,
        align: 'center',
        render: (text, record) => (
          <Fragment>
            <a
              onClick={() => this.showAddNewModal(record)}
              className={styles.actionButton}
              disabled={record.defaultSet === '1'}
            >
              <Icon type="plus" className={styles.editButton} />
              {'新增子类'}
            </a>
            <a onClick={() => this.handleEditClick(record)} className={styles.actionButton}>
              <Icon type="edit" className={styles.editButton} />
              {'编辑'}
            </a>
            <Popconfirm
              placement="topRight"
              title="此操作不会修改已有的商品信息，确定删除吗？"
              onConfirm={() => this.deleteItem(record)}
              onCancel={this.cancelDelete}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton} disabled={record.defaultSet === '1'}>
                <Icon type="delete" className={styles.editButton} />
                {'删除'}
              </a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderWrapperCustom title="商品分类列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <Table
              showHeader={false}
              loading={loading}
              dataSource={list}
              columns={columns}
              pagination={false}
              style={{
                paddingBottom: '30px',
              }}
            />
          </div>
        </Card>
        <OperateModal
          visible={updateItemVisible}
          mode="update"
          showRoot
          treeData={list}
          metaData={metaData}
          category={category}
          dispatch={dispatch}
          afterOK={this.afterUpdateItemModalOk}
          afterCancel={this.afterUpdateItemModalCancel}
        />
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default List;
